<template>
  <view class="content">
    <!-- 侧边栏菜单 -->
    <side-menu :visible="sideMenuVisible" @close="closeSideMenu" />

    <!-- 顶部导航 -->
    <page-header>
      <!-- 左侧更多按钮 -->
      <template #left>
        <view class="header-icon" @click="showMenu">
          <image class="icon-svg" src="/static/svgs/view-list.svg"></image>
        </view>
      </template>

      <!-- 中间Logo -->
      <template #center>
        <image class="header-logo" src="/static/logo/logo.png"></image>
      </template>

      <!-- 右侧添加按钮 -->
      <template #right>
        <view class="header-icon" @click="addTodo">
          <image class="icon-svg" src="/static/svgs/add.svg"></image>
        </view>
      </template>
    </page-header>

    <!-- 主体内容 -->
    <view class="page-body">
      <!-- 标签选择栏 -->
      <tab-selector
        :tabs="tabs"
        v-model:activeTab="activeTabIndex"
        @change="handleTabChange"
      />

      <!-- 待办列表 -->
      <scroll-view
        class="todo-container"
        scroll-y="true"
        @scrolltolower="loadMore"
      >
        <todo-list
          :todos="filteredTodos"
          @toggle-complete="toggleTodoComplete"
          @edit="editTodo"
          @delete="deleteTodo"
          @update="updateTodo"
        />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import pageHeader from "@/components/pageHeader.vue";
import TabSelector from "@/components/TabSelector.vue";
import TodoList from "@/components/TodoList.vue";
import SideMenu from "@/components/SideMenu.vue";
import { todoApi } from "@/api";

// 页面数据
const activeTabIndex = ref(0);
const sideMenuVisible = ref(false);

// 标签和待办数据
const todoListData = ref([]);
const tabs = ref([]);
const allTodos = ref([]);

// 根据当前标签筛选待办
const filteredTodos = computed(() => {
  if (!todoListData.value.length || activeTabIndex.value < 0) {
    return [];
  }

  const currentLabelData = todoListData.value[activeTabIndex.value];
  if (!currentLabelData || !currentLabelData.todoItems) {
    return [];
  }

  // 转换数据格式以适配TodoList组件
  return currentLabelData.todoItems.map((item) => ({
    id: item.todoItemId,
    content: item.content,
    completed: false, // API返回的数据中没有completed字段，默认为false
    createdAt: item.createdAt,
    updatedAt: item.updatedAt,
    labelId: currentLabelData.labelId,
    labelName: currentLabelData.labelName,
  }));
});

// 页面方法
const handleTabChange = (tab, index) => {
  console.log("Tab changed:", tab.name, index);
};

const toggleTodoComplete = async (id) => {
  try {
    // 在当前标签的todoItems中查找待办
    const currentLabelData = todoListData.value[activeTabIndex.value];
    if (!currentLabelData || !currentLabelData.todoItems) {
      return;
    }

    const todoIndex = currentLabelData.todoItems.findIndex(
      (item) => item.todoItemId === id
    );
    if (todoIndex === -1) {
      uni.showToast({
        title: "待办不存在",
        icon: "none",
      });
      return;
    }

    const todoItem = currentLabelData.todoItems[todoIndex];

    // 调用更新API，将待办设置为已完成
    const response = await todoApi.updateTodo({
      id: id,
      isCompleted: true,
      content: todoItem.content, // 传入原内容
      labels: [currentLabelData.labelId], // 传入当前标签ID
    });

    if (response.success) {
      // 从未完成列表中移除
      currentLabelData.todoItems.splice(todoIndex, 1);

      // 通知已完成待办页面刷新数据
      uni.$emit("completedTodoStatusChanged");
      uni.$emit("refreshCompletedTodoList");

      uni.showToast({
        title: "已标记为完成",
        icon: "success",
      });
    } else {
      uni.showToast({
        title: response.msg || "操作失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("切换待办完成状态失败:", error);
    uni.showToast({
      title: "操作失败，请重试",
      icon: "none",
    });
  }
};

const editTodo = (id) => {
  // 由TodoList组件直接处理，无需在此实现
};

const deleteTodo = (id) => {
  uni.showModal({
    title: "删除待办",
    content: "确定要删除这个待办事项吗？",
    success: async function (res) {
      if (res.confirm) {
        try {
          // 调用删除API
          const response = await todoApi.deleteTodo({ id: id });

          if (response.success) {
            // 在当前标签的todoItems中查找待办
            const currentLabelData = todoListData.value[activeTabIndex.value];
            if (!currentLabelData || !currentLabelData.todoItems) {
              return;
            }

            const todoIndex = currentLabelData.todoItems.findIndex(
              (item) => item.todoItemId === id
            );
            if (todoIndex === -1) return;

            const todoItem = currentLabelData.todoItems[todoIndex];

            // 标记为已删除
            todoItem.deleted = true;

            // 从列表中移除
            currentLabelData.todoItems.splice(todoIndex, 1);

            // 发送到回收站
            uni.$emit("todoDeleted", todoItem);

            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: response.msg || "删除失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("删除待办失败:", error);
          uni.showToast({
            title: "删除失败，请重试",
            icon: "none",
          });
        }
      }
    },
  });
};

const setReminder = (id) => {
  uni.showToast({
    title: "设置提醒功能开发中",
    icon: "none",
  });
};

const addTodo = () => {
  uni.navigateTo({
    url: "/pages/add-todo/add-todo",
  });
};

const showMenu = () => {
  sideMenuVisible.value = true;
};

const closeSideMenu = () => {
  sideMenuVisible.value = false;
};

const loadMore = () => {
  console.log("加载更多待办...");
};

const updateTodo = (updateData) => {
  // 在当前标签的todoItems中查找并更新
  const currentLabelData = todoListData.value[activeTabIndex.value];
  if (!currentLabelData || !currentLabelData.todoItems) {
    return;
  }

  const todoIndex = currentLabelData.todoItems.findIndex(
    (item) => item.todoItemId === updateData.id
  );
  if (todoIndex !== -1) {
    currentLabelData.todoItems[todoIndex].content = updateData.content;
  }
};

// 获取待办列表数据的方法
const loadTodoList = async () => {
  try {
    const res = await todoApi.getTodoList();
    if (res.success && res.data) {
      // 存储完整的数据
      todoListData.value = res.data;

      // 生成标签数据
      tabs.value = res.data.map((item, index) => ({
        id: item.labelId,
        name: item.labelName,
        index: index,
      }));

      // 扁平化所有待办数据以供其他功能使用
      allTodos.value = res.data.flatMap((label) =>
        label.todoItems.map((todo) => ({
          ...todo,
          id: todo.todoItemId, // 统一id字段名
          labelId: label.labelId,
          labelName: label.labelName,
        }))
      );
    }
  } catch (error) {
    console.error("获取待办列表失败:", error);
  }
};

// 页面加载
onMounted(async () => {
  console.log("Todo页面已加载");

  // 获取待办列表数据
  await loadTodoList();

  // 监听从编辑页返回的数据
  uni.$on("updateTodo", (todoData) => {
    // 重新加载数据以确保数据一致性
    loadTodoList();
  });

  // 监听添加待办事件
  uni.$on("addTodo", (todoData) => {
    // 重新加载数据以获取最新的待办列表
    loadTodoList();
  });

  // 监听删除待办事件
  uni.$on("deleteTodo", (todoId) => {
    // 从所有标签的列表中删除
    for (let labelData of todoListData.value) {
      labelData.todoItems = labelData.todoItems.filter(
        (item) => item.todoItemId !== todoId
      );
    }
  });

  // 监听取消完成待办事件
  uni.$on("todoUncompleted", (todoData) => {
    // 重新加载数据
    loadTodoList();

    // 通知已完成待办页面状态已更新
    uni.$emit("completedTodoStatusChanged");
  });

  // 监听从回收站恢复待办事件
  uni.$on("todoRestored", (todoData) => {
    // 重新加载数据
    loadTodoList();

    uni.showToast({
      title: "待办已恢复",
      icon: "success",
    });
  });

  // 监听永久删除待办事件
  uni.$on("permanentDeleteTodo", (todoId) => {
    // 从所有标签的列表中删除
    for (let labelData of todoListData.value) {
      labelData.todoItems = labelData.todoItems.filter(
        (item) => item.todoItemId !== todoId
      );
    }
  });

  // 监听标签数据刷新事件
  uni.$on("refreshLabels", () => {
    loadTodoList();
  });

  // 监听待办列表刷新事件
  uni.$on("refreshTodoList", () => {
    loadTodoList();
  });
});

// 组件销毁时清除事件监听
onUnmounted(() => {
  uni.$off("updateTodo");
  uni.$off("addTodo");
  uni.$off("deleteTodo");
  uni.$off("todoUncompleted");
  uni.$off("todoRestored");
  uni.$off("permanentDeleteTodo");
  uni.$off("refreshLabels");
  uni.$off("refreshTodoList");
});
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  width: 100%;
  overflow-x: hidden;
}

.page-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  position: relative;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  padding-top: 80rpx; /* 为固定的tab-selector留出空间 */
}

.todo-container {
  flex: 1;
  padding: 0 20rpx;
  box-sizing: border-box;
  width: 100%;
}

.header-icon {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-svg {
  width: 44rpx;
  height: 44rpx;
  color: #333333;
}

.header-logo {
  width: 60rpx;
  height: 60rpx;
}

/* 添加固定tab-selector的样式 */
:deep(.tab-selector) {
  position: fixed;
  top: calc(var(--status-bar-height) + 90rpx); /* 根据page-header的高度调整 */
  left: 0;
  right: 0;
  z-index: 100;
}
</style>
